package com.shoulder.resourceserver.handler;

import com.shoulder.core.utils.JsonUtils;
import com.shoulder.core.api.ApiResult;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class SecurityAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.info("请求被拒绝:{} ", request.getRequestURI());
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        ApiResult<Object> apiResult = ApiResult.badRequest();
        apiResult.setMsg("权限不足");
        writer.write(JsonUtils.obj2Json(apiResult));
        writer.flush();
        writer.close();
    }
}